package com.jsp.study.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.catalina.core.ApplicationPart;

@WebServlet("/UploadServlet")
@MultipartConfig(location="d:/logs")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public UploadServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		String path = "d:/logs/upload";
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdir();
		}
		Part p = request.getPart("file1");
		if (p.getContentType().contains("image")) {
			String header = p.getHeader("content-disposition");
//			String submittedFileName = p.getSubmittedFileName();
			String fileName = header.substring(header.lastIndexOf("\\")+1,header.lastIndexOf("\""));
			p.write(path + File.separator + fileName);
			out.write("文件上传成功");
		} else {
			out.write("请选择图片文件！");
		}
	}

}
